package com.baizw.cultivation.module.admin.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baizw.cultivation.common.annotation.method.OnlyOneMapper;
import com.baizw.cultivation.common.exception.GlobalException;
import com.baizw.cultivation.common.response.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 测试接口
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年05月20日 10:41
 */
@RestController
@Api(tags = "测试接口")
@RequestMapping("/api/uniqueness")
public class TestController {

    @Autowired
    private OnlyOneMapper oneMapper;

    @ApiOperation("数据唯一性带key")
    @GetMapping("/onlyOne/{tableName}/{key}/{values}")
    public ResultBean testOnlyOne(@PathVariable String tableName, @PathVariable String key, @PathVariable Object[] values) {
        if (StrUtil.isNotBlank(tableName)) {
            try {
                Object[] objects = ArrayUtil.isArray(values) ? ArrayUtil.cast(Object.class, values) : new Object[]{values};
                List<Object> dataExistList = oneMapper.dataExist(tableName, StrUtil.toUnderlineCase(key), objects);
                String messageTemplate = "数据【{}】已存在，请核验";
                String message = dataExistList.parallelStream().map(x -> StrUtil.format(messageTemplate, x))
                        .collect(Collectors.joining(StrUtil.LF));
                return ResultBean.isTrue(dataExistList.size() == 0, message);
            } catch (Exception e) {
                throw new GlobalException("数据库唯一性校验异常", e);
            }
        }
        return ResultBean.ok();
    }
}
